package com.bi.design.controller;

import com.bi.design.dto.ResetPasswordDTO;
import com.bi.design.entity.SysUser;
import com.bi.design.query.SysUserPageQuery;
import com.bi.design.service.SysUserService;
import com.bi.design.tools.ApiResult;
import com.bi.design.tools.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/sys-user/")
public class SysUserController {
    private final SysUserService sysUserService;

    @PostMapping("/page")
    public ApiResult<PageInfo<SysUser>> getPageQuery(@RequestBody SysUserPageQuery dto) {
        return ApiResult.ok(sysUserService.getPageQuery(dto));
    }

    @PostMapping("/add-or-edit")
    public ApiResult<Long> addAndEdit(@Validated @RequestBody SysUser dto) {
        return ApiResult.ok(sysUserService.addAndEdit(dto));
    }

    @PostMapping("/resetPassword")
    public ApiResult<String> resetPassword(@Validated @RequestBody ResetPasswordDTO dto) {
        final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        SysUser user = new SysUser();
        user.setId(dto.getId());
        if (StringUtils.hasLength(dto.getPassword())) {
            // 修改密码
            user.setPassword(passwordEncoder.encode(dto.getPassword()));
        } else {
            // 重置密码
            user.setPassword(passwordEncoder.encode("12345678"));
        }
        sysUserService.edit(user);
        return ApiResult.ok();
    }


    @PutMapping("/state/{id}/{state}")
    public ApiResult<String> state(@PathVariable Long id, @PathVariable Boolean state) {
        if (id.equals(1L)) {
            return ApiResult.failed("系统默认管理员不可被禁用！");
        }
        SysUser user = new SysUser();
        user.setId(id);
        user.setDisabled(state);
        sysUserService.edit(user);
        return ApiResult.ok();
    }

    /**
     * 删除-删除用户
     */
    @DeleteMapping("/del/{uid}")
    public ApiResult<String> delete(@PathVariable Long uid) {
        if (uid.equals(1L)) {
            return ApiResult.failed("系统默认管理员不可被手动删除！");
        }
        sysUserService.removeById(uid);
        return ApiResult.ok();
    }

}

